package com.gr.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gr.entity.*;
import com.gr.service.ISkuInfoService;
import com.gr.service.ISpuAttrValueService;
import com.gr.service.ISpuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * spu信息 前端控制器
 * </p>
 *
 * @author guoran
 * @since 2022-05-11
 */
@RestController
@RequestMapping("/spuInfo")
public class SpuInfoController {
    @Autowired
    private ISpuInfoService spuInfoService;
    @Autowired
    private ISpuAttrValueService spuValueService;
    @Autowired
    private ISkuInfoService skuInfoService;
    @GetMapping("/selectSpuByCategoryId/{categoryId}")
    public ResultEntity<IPage<SpuInfo>> selectSpuByCategoryId(@PathVariable("categoryId")Integer categoryId,Integer pageNo,Integer pageSize){
        IPage<SpuInfo> page=new Page<>(pageNo,pageSize);
        QueryWrapper<SpuInfo> wrapper=new QueryWrapper<>();
        wrapper.eq("category_id",categoryId);
        IPage<SpuInfo> pages = spuInfoService.page(page, wrapper);
        return ResultEntity.ok(pages);
    }

    /** 只需要添加需要用户添加的数据
     * 不能用list 因为Map中key-value两个都是要添加的数据
     * @param dto
     * @return
     */
    @PostMapping("/add")
    public ResultEntity add(@RequestBody SpuDto dto){
        spuInfoService.save(dto.getSpu());
        Map<String, String> attrValues = dto.getAttrValues();
        Set<Map.Entry<String, String>> entries = attrValues.entrySet();
        for (Map.Entry<String,String> entry:entries){
            SpuAttrValue value = new SpuAttrValue(Long.parseLong(entry.getKey()), entry.getValue());
            spuValueService.save(value);
        }
        return ResultEntity.ok();
    }

    @GetMapping("/selectSkusBySpuId/{spuId}")
    public ResultEntity<List<SkuInfo>> selectSkusBySpuId(@PathVariable("spuId")Integer spuId){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("spu_id",spuId);
        List<SkuInfo> list = skuInfoService.list(wrapper);
        return ResultEntity.ok(list);
    }
}

